package com.example.firstproject.security;

import com.example.firstproject.entity.User;
import com.example.firstproject.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;


@Service
public class MyUserDetailsService  implements UserDetailsService {



    @Autowired
    private UserMapper userMapper;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.getByUsername(username);
        List<GrantedAuthority> grantedAuthorityList;
        if (user == null)
            throw new UsernameNotFoundException("用户名不存在");
        else {
            String password = new BCryptPasswordEncoder().encode(user.getPassword());
            grantedAuthorityList = new LinkedList<>();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE-admin");
            grantedAuthorityList.add(simpleGrantedAuthority);

        }
        return new org.springframework.security.core.userdetails.User(username, new BCryptPasswordEncoder().encode(user.getPassword()), grantedAuthorityList);
    }
}
